<html>
<head>
<script>
    tabUrls = {}
    urlData = {}

    function getUrlData(tabId)
    {
        return urlData[tabId];
    }
    function getUrl(tabId)
    {
        return tabUrls[tabId];
    }    

    function jreq(url, f, onError, depth) {
        var xhr = new XMLHttpRequest();
        try {
            /*xhr.onreadystatechange =*/
            function processData() {
                if (xhr.readyState === 4) {
                    var text = xhr.responseText;
                    if (text == "{error: 500}")
                    {
                        if (depth >= 5)
                        {
                            onError ("error 500 for " + url +'. Gave up after '+ depth + ' tries.');
                            return;
                        }
                        return jreq(url, f, onError, depth?(depth+1):1);
                    }
                    var js = null;
                    try { // Needed because reddit returns raw html for strange urls (eg., : chrome://)
                        js = JSON.parse(text);
                    } catch(e) {
                        console.log("Expected JSON from:",url ,"Instead got:", text);
                        onError("JSON.parse exception: " + e + "|" + text);
                    }
                    f(js);
                }
            };
            xhr.onerror = function(err) {
                console.log("xhr error:", err);
                onError("xhr error: " + e);
            };
            xhr.open("GET", url, true);
            xhr.onload = processData;
            xhr.send(null);
        } catch(e) {
            console.log("Exception:", e);
            onError("jreq exception: " + e);
        }
    }
    
    function stripUrlHash( url )
    {
        return url.split('#', 1)[0]
    }

    function updateTabBadge(tab)
    {
        children = urlData[tab.id]
        l = children.length;
        text = l?(''+l):'NEW';
        chrome.browserAction.setBadgeText({text: text , tabId:tab.id});
    }

    function tabChangedUrl( tab, old_url, new_url )
    {
        // This is the part where I connect to reddit to check stats about the url !
        chrome.browserAction.setBadgeText({text: '...' , tabId:tab.id});

        function onError(text)
        {
            console.error("Error: " + text);
            chrome.browserAction.setBadgeText({text: 'ERR' , tabId:tab.id});
        }

        /*var req = new XMLHttpRequest();
        req.open( "GET", "http://www.reddit.com/api/info.json?url="+new_url, true);
        req.onload = processData;
        req.send(null);*/

        res = jreq("http://www.reddit.com/api/info.json?url="+new_url, processData, onError);

        function processData(js) {
            if (js.kind != 'Listing')
            {
                onError("Error, js kind is: " + js.kind);
                console.log("Error, js kind is: " + js.kind);
            }

            urlData[tab.id] = js.data.children;
            updateTabBadge(tab);
        }
        
    }

    function checkTabUpdate( tab )
    {
       
        url = stripUrlHash(tab.url);
        if (tab.id in tabUrls)
        {
            if ( tabUrls[tab.id] != url )
            {
                tabChangedUrl( tab, tabUrls[tab.id], url);
                tabUrls[tab.id] = url;
            }
            else
            {
                updateTabBadge(tab);    // tab didn't change, but may need to refresh badge
            }
        }
        else
        {
            tabChangedUrl( tab, '', url);
            tabUrls[tab.id] = url
        }
    }

    chrome.tabs.getAllInWindow(null, function (tabs)
    {
        tabs.forEach( function(tab)
        {
            checkTabUpdate( tab );
        }
        );
    }
    );


    chrome.browserAction.setBadgeBackgroundColor({color: [128,128,255,255]});
    // Called when the url of a tab changes.
    function checkForValidUrl(tabId, changeInfo, tab) {
        checkTabUpdate( tab );
    };

    // Listen for any changes to the URL of any tab.
    chrome.tabs.onUpdated.addListener(checkForValidUrl);
</script>
</head>
</html>

